
//
//  UserAccountViewModel.swift
//  swiftImitationWeibo
//
//  Created by 杨果果 on 16/7/12.
//  Copyright © 2016年 yang. All rights reserved.
//

import UIKit

class UserAccountViewModel: NSObject {
    
    //创建的单例
    static let sharedUserAccountViewModel: UserAccountViewModel = UserAccountViewModel()
    // 获取用户对象从沙盒内解档的对象
    var userAccount: UserAccountModel? {
//        print(UserAccountModel.loadUserAccount())
        return UserAccountModel.loadUserAccount()
    }
    //构造函数私有化
    private override init() {
        super.init()
    }
    //封装accessToken 判断是否为登陆
    var isLogin: Bool{
        return accessToken != nil
    }
    //判断accessToken 有没有值     判断是否过期
    var accessToken: String? {
        guard let token = userAccount?.access_token else{
            return nil
        }
        //比较有效时间
        let result = userAccount?.expiresDate?.compare(NSDate())
        if result == NSComparisonResult.OrderedDescending {
            return token
        }else {
            return nil
        }
    }
    
    //通过授权码code  获取accesstoken
    func requestAccesstoken(code: String, callBack: (isSuccess: Bool) -> ()) {
                NetworkingTools.sharedTools.requestAccesstoken(code) { (resquest, error) -> () in
            if error != nil {
                print(error)
                callBack(isSuccess: false)
                return
            }
            guard let dic = resquest as? [String: AnyObject] else{
                print("不是一个正确的json格式")
                callBack(isSuccess: false)
                return
            }
            let userAccount = UserAccountModel(dic: dic)
//            print(userAccount)
            
            //通过accesstoken 和 uid 获取用户信息
                    self.requestUserInfo(userAccount, callBack: callBack)
            
            
        }
        
    }
    private func requestUserInfo(userAccount: UserAccountModel,callBack: (isSuccess: Bool) -> () ) {
                //MARK --  使用工具类
        NetworkingTools.sharedTools.requestUserInfo(userAccount) { (resquest, error) -> () in
            if error != nil{
                print(error)
                callBack(isSuccess: false)
                return
            }
            guard let dic = resquest as? [String: AnyObject] else {
                callBack(isSuccess: false)
                return
            }
            let name = dic["name"]
            let avatar_large = dic["avatar_large"]
            
            userAccount.name = name as? String
            userAccount.avatar_large = avatar_large as? String
            
            //保存用户对象
            
            let result = userAccount.saveUserAccount()
            print(result)
            if result {
                callBack(isSuccess: true)
            }else{
                callBack(isSuccess: false)
            }
//            print(userAccount)
            
        }
        
        
    }

}
